package com.fruit.api.controller.fruit;

import com.fruit.api.controller.BaseController;
import com.fruit.bean.entity.fruit.FruitShelfInfo;
import com.fruit.bean.entity.fruit.FruitShoppingCartDto;
import com.fruit.bean.entity.fruit.FruitShoppingCartInfo;
import com.fruit.bean.vo.front.Rets;
import com.fruit.service.fruit.FruitShelfService;
import com.fruit.service.fruit.FruitShoppingCartService;
import com.fruit.utils.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/fruit/shopping/cart")
public class FruitShoppingCartController extends BaseController {

    @Autowired
    private FruitShoppingCartService shoppingCartService;

    @Autowired
    private FruitShelfService shelfService;

    /**
     * 添加商品到购物车
     * @return
     */
    @RequestMapping("/add")
    public Object addGoodsToShoppingCart(@RequestBody FruitShoppingCartDto shoppingCartDto){
        Long shelfId = shoppingCartDto.getShelfId();
        double shoppingNumber = shoppingCartDto.getFruitWeight();
        //确认库存是否足够
        FruitShelfInfo fruitShelfInfo = shelfService.get(shelfId);
        if(fruitShelfInfo.getFruitSellNumber() < shoppingNumber){
            //库存不足
            return Rets.failure("库存不足，请重新选择购买数量");
        }
        HttpServletRequest request = HttpUtil.getRequest();
        FruitShoppingCartInfo shoppingCartInfo = new FruitShoppingCartInfo();
        shoppingCartInfo.setUserId(shoppingCartDto.getUserId());
        shoppingCartInfo.setFruitShelfId(shelfId);
        shoppingCartInfo.setShoppingNumber(shoppingNumber);
        shoppingCartService.insert(shoppingCartInfo);
        return Rets.success();
    }

    /**
     * 删除购物车信息，支持多选
     * @param shoppingCartIds 购物车id列表
     * @return
     */
    @RequestMapping("/del")
    public Object deleteShoppingCart(List<Long> shoppingCartIds){
        shoppingCartService.delete(shoppingCartIds);
        return Rets.success();
    }
}
